/*	获得用户ID
#include <unistd.h>
#include <sys/types.h>

uid_t getuid();		// 获得实际用户标识符 : 调用该进程的标识符
uid_t geteuid();	// 获得有效用户标识符 : 进程目前运行的用户标识符

gid_t getgid();		// 获得实际的组标识符
gid_t getegid();	// 获得有效的组标识符
*/

/* 设置用户ID
#include <unistd.h>
#include <sys/types.h>

int setuid(uid_t uid);
int seteuid(uid_t euid);

int setgid(gid_t gid);
int setegid(gid_t egid);

int setreuid(uid_t ruid, uid_t euid);
int setregid(gid_t rgid, gid_t egid);

int setfsuid(uid_t fsuid);
int setfsgid(gid_t fsgid);
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include "error.h"
#include <sys/stat.h>
#include <stdarg.h>
#include <fcntl.h>
#include <errno.h>

void enhancedperms(void);
void normalperms(void);
void tryopen(void);
int ruid, euid;

int main(int argc, char * argv[]) {
	ruid = getuid();
	euid = geteuid();

	normalperms();

	if(ruid == euid) {
		fprintf(stdout, "euid=%d: warnig: this program wasn't marked setuid in the filesystem.\n", euid);
		fprintf(stdout, "euid=%d: or you running the program at root.\n", euid);
	}
	
	tryopen();
	enhancedperms();
	tryopen();
	normalperms();
	fprintf(stdout, "euid=%4d: Exit now.\n", euid);

	return 0;
}

void enhancedperms(void) {
	if(seteuid(euid) == -1) {
		fprintf(stdout, "Euid=%d: Railed to switch to enhanced permissions: %s.\n", euid, sys_errlist[errno]);
		exit(255);
	} else {
		fprintf(stdout, "Euid=%d: Switch to enhanced permissions.\n", euid);
	}
}

void normalperms(void) {
	if(seteuid(ruid) == -1) {
		fprintf(stdout, "Euid=%d: Railed to switch to normal permissions: %s.\n", euid, sys_errlist[errno]);
		exit(255);
	} else {
		fprintf(stdout, "Euid=%d: Switch to normal permissions.\n", euid);
	}
}

void tryopen(void) {
	char * filename = "/etc/shadow";
	int result;

	if((result = open(filename, O_RDONLY)) == -1) {
		fprintf(stdout, "Euid=%d: Open failed %s.\n", euid, sys_errlist[errno]);
	} else {
		fprintf(stdout, "Euid=%d: Open was successful.\n", euid);
		close(result);
	}
}
